package cn.itcast.login;

import cn.itcast.base.BaseController;
import cn.itcast.domain.Module;
import cn.itcast.domain.User;
import cn.itcast.service.module.ModuleService;
import cn.itcast.service.user.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class LoginController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;


    /*@RequestMapping("/login")
    public String login(String email,String password) {

        //1 登录不成功（login.jsp）
        if(UtilFuns.isEmpty(email) || UtilFuns.isEmpty(password)){
            // 登录失败--账号密码为空
            return "forward:login.jsp";
        }

        //2 账号密码为空---去数据库查询
        User user=userService.findByUser(email);
        if(user==null || !user.getPassword().equals(password)){
            // 登录失败--账号密码不匹配
            request.setAttribute("error","账号或密码错误...");
            return "forward:login.jsp";
        }

        //3 登录成功
        session.setAttribute("loginUser",user);

        //4 控制：想办法在页面展示出当前登录用户应该具备的菜单吧
        List<Module> menus=moduleService.findMenus(user);
        session.setAttribute("modules",menus);
        return "home/main";
    }*/


    @RequestMapping(value = "/login",name = "shiro做登录认证")
    public String login(String email,String password) {

        try {

            //shiro认证
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken uptoken=new UsernamePasswordToken(email,password);
            subject.login(uptoken); //入口开始

            //登录认证成功的用户放入session
            User user =(User)subject.getPrincipal();
            session.setAttribute("loginUser",user);
            // 将该登录用户的菜单查询出来在页面动态构造菜单
            List<Module> menus=moduleService.findMenus(user);
            session.setAttribute("modules",menus);

        }catch (Exception e){
            // 登录失败--账号密码不匹配
            request.setAttribute("error","账号或密码错误...");
            return "forward:login.jsp";
        }

        return "home/main";
    }


    //退出
    @RequestMapping(value = "/logout",name="用户登出")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();//shiro的登录用户登出
        subject.logout();
        return "forward:login.jsp";
    }

    @RequestMapping("/home")
    public String home(){

        return "home/home";
    }
}
